package com.spring.housing1.util;



import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.spring.housing1.returnType.CommenResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GeiWxPhone {
    private final Logger log = LoggerFactory.getLogger(GeiWxPhone.class);
    private  RestTemplate restTemplate;

    public CommenResult<Map> getPhone(String grant_type, String AppSecret, String appId, String code, JdbcTemplate jdbcTemplate) throws Exception {
//        使用当前对象作为锁头(spring默认为单例)获取手机号
        synchronized (this){

            if(code == null || code.equals("")){
                throw new NullPointerException("code为空!");
            }
            //获取access_token
            String URL= "https://api.weixin.qq.com/cgi-bin/token";
            Map param = new ConcurrentHashMap();
            param.put("grant_type",grant_type);
            param.put("secret",AppSecret);
            param.put("appid",appId);
            String request = HttpRequestUtil.getRequest(URL, param);
            JSONObject res  = JSONUtil.parseObj(request);
            String  access_token =  res.get("access_token").toString();


            //openId
            String url_openId = "https://api.weixin.qq.com/sns/jscode2session";
            Map param_oid = new ConcurrentHashMap();
            param_oid.put("grant_type","authorization_code");
            param_oid.put("secret",AppSecret);
            param_oid.put("appid",appId);
            param_oid.put("js_code",code);
            JSONObject res_openId = JSONUtil.parseObj(HttpRequestUtil.getRequest(url_openId, param_oid));
            if(res_openId.get("errcode")!=null ){
                throw new NullPointerException("获取openId失败!code失效");
            }
            String  openId =  res_openId.get("openid").toString();
            String session_key = res_openId.get("session_key").toString();
            log.info("{openId为: {}",openId);

//            设置token令牌
            String uu_token = java.util.UUID.randomUUID().toString();
            log.info("当前登录的session_value为:{}",uu_token);
            Map resm = new HashMap();
            if(jdbcTemplate.queryForMap("select count(*) from  login_wx where open_id = ?",openId).get("count(*)").toString().equals("1")){
                jdbcTemplate.update("update  login_wx set  session_value = ?  where open_id = ?",uu_token,openId);
                resm.put("openid",openId);
                resm.put("session_value",uu_token);
                return   new CommenResult<>(200,"获取openid,session_key,session_value成功",resm);
            }
            jdbcTemplate.update("insert into login_wx (open_id,session_value) values (?,?)",openId,uu_token );
            resm.put("openid",openId);
            resm.put("session_value",uu_token);
            return   new CommenResult<>(200,"获取openid,session_key,session_value成功",resm);
        }

    }
}
